const  MongoClient = require("mongodb"). MongoClient;

const url="mongodb://localhost:27017";
//////增 删 改 查
function connect(callback){
    MongoClient.connect(url,(err,db)=>{
        if(err) throw err;
        callback(db)
    })
}
//////增
module.exports.insert=(dbname,colname,obj,callback)=>{
    connect((db)=>{
            if(!(obj instanceof Array)){
                obj=[obj]
            }
            db.db(dbname).collection(colname).insertMany(obj,(err,result)=>{
                if(err) throw err;
                console.log("插入数据成功");
                db.close();
               
              callback(result);
            })
    })
}
//删
module.exports.del=(dbname,colname,obj,callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).deleteMany(obj,(err,result)=>{
            if(err) throw err;
            console.log("删除");
            db.close();
          callback(result)
        })
    })

}
//改
module.exports.update=(dbname,colname,obj,ob,callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).updateMany(obj,{$set:ob},(err,result)=>{
            if(err) throw err;
            console.log("改");
            db.close();
            callback(result);
        })
    })
}

//查
module.exports.find=(dbname,colname,obj,callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).find(obj).toArray((err,result)=>{
            if(err) throw err;
            console.log("查询成功");
            callback(result);
        })
    })
}

module.exports.search=(dbname,colname,obj,skip=0,limit=0,callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).find(obj).skip(skip).limit(limit).toArray((err,result)=>{
            if(err) throw err;
            console.log("查询成功");
            callback(result);
        })
    })
}